package org.microsites.util;

import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import net.lemnik.eodsql.BaseQuery;
import net.lemnik.eodsql.DataSet;
import net.lemnik.eodsql.InvalidDataTypeException;
import net.lemnik.eodsql.InvalidQueryException;
import net.lemnik.eodsql.QueryTool;
import net.lemnik.eodsql.TypeMapper;

public abstract class EodDaoSupport {
	
	private DataSource dataSource;

	public void setDataSource(DataSource ds) {
		this.dataSource = ds;
	}
	
	public void addTypeMapper(Class<?> cls, TypeMapper<?> tm) {
		QueryTool.getTypeMap().put(cls, tm);
	}

	public <T extends BaseQuery> T getQuery(Class<T> query) throws InvalidDataTypeException, InvalidQueryException {
		try {
			return QueryTool.getQuery(this.dataSource, query);
		} catch (RuntimeException ex) {
			ex.printStackTrace();
			throw ex;
		}
	}

	public <T> List<T> select(Class<T> type, String query, Object... parameters) throws InvalidDataTypeException, InvalidQueryException {
		DataSet<T> dataset = QueryTool.select(this.dataSource, type, query, parameters);

		List<T> list = new ArrayList<T>(dataset);
		dataset.close();
		
		return list;
	}
}
